<?php
session_start();
if ($_SESSION['user'] == "") {
    ?>
    <script>
        alert('当前未登录！');
        window.location.href = '../login.html';
    </script>
    <?php
}
try {
$db = new PDO('mysql:dbname=liaotian;host=106.14.7.147', 'root', '123456');

//更新user_room中的房间状态status=0，说明离开房间
$update2 = $db->prepare('UPDATE user_room set status=:status  WHERE username=:username');
$data=[
    ':username' => $_SESSION['user'],
    ':status' =>0
];
if ($update2->execute($data) === false) {
    print_r($update2->errorInfo());
}
$re = $update2->fetch();
//查询在线人数
$searchNum = $db->prepare('select user_room.roomId,room.Num from user_room 
                            LEFT JOIN room on room.roomId=user_room.roomId 
                            where user_room.username=:username');
$data=[
    ':username' => $_SESSION['user']
];
if ($searchNum->execute($data) === false) {
    print_r($searchNum->errorInfo());
}
$reNum = $searchNum->fetch();
if($reNum['Num'] >0){
    $reNum['Num'] = $reNum['Num'] -1;
//在room表中更新在线人数 Num-1
    $update = $db->prepare('UPDATE room set Num=:Num WHERE roomId=:roomId');
    $data=[];
    $data[':roomId'] = $reNum['roomId'];
    $data[':Num'] = $reNum['Num'];
    if ($update->execute($data) === false) {
        print_r('num-1:'.$update->errorInfo());
    }
    $re = $update->fetch();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>大厅</title>
    <link href="../css/room.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
} catch (PDOException $e) {
    echo 'Connection failed';
}
?>
<form id="myForm" action="/action/roomAction.php" method="post">
<div id="room">
    <div class="top">
        <div class="top_left"><h1>失乐园大厅</h1></div>
        <div class="top_center">
            <input class="search_text" type="text" name="roomId" placeholder="输入房间号码">
            <input id="submit" class="search_submit" type="submit" value="搜索">
        </div>
        <div class="top_right">
            
            <div class="top_right_update">
                <a href="updateUser.php?username=<?=$_SESSION['user']?>">修改用户信息</a>
                <a href="createRoom.php">创建聊天室</a>
            </div>
            <div class="top_right_close">
            <a href="../login.html">退出</a>
            </div>
        </div>
        <div style="clear: both"></div>
    </div>
    <div class="foot" id="chat">

    </div>
</div>
</form>
<script>
    //所有房间同步刷新
    var messageRoom = function () {
        var searchMessage = document.getElementById('chat');
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status != 200) {
                    console.log("服务器异常！");
                } else {
                    var result = JSON.parse(this.responseText);
                    searchMessage.innerHTML = "";
                    if (result.message.length == 0) return;
                    for (var i = 0; i < result.message.length; i++) {
                        searchMessage.insertAdjacentHTML('beforeend',
                            '<div class="foot_room">'+
                            '<div class="foot_room_img">'+
                            '<div class="name_num">'+
                            '<a href="liaotian.php?roomId='+result.message[i].roomId+'">'+
                            result.message[i].roomName+
                            '</a>'+
                            '</div>'+
                            '<a href="liaotian.php?roomId='+result.message[i].roomId+'">'+
                            '<img src="'+result.message[i].roomImg+'" />'+
                            '</a>'+
                            '</div>'+
                            '<div class="foot_room_name">'+
                            '<a href="liaotian.php?roomId='+result.message[i].roomId+'">'+
                            '<div class="name_name">房号：'+
                            result.message[i].roomId+
                            '</div>'+
                            '</a>'+
                            '</div>'+
                            '</div>'
                        )
                    }
                }
            }
        };
        xhr.open('post', '/action/messageRoom.php');
        xhr.send();
    };
    setInterval(messageRoom, 1000);
//搜索房间号码并进入房间
    var submitButton = document.getElementById('submit');
    var myFormElement = document.getElementById('myForm');
    submitButton.onclick = function (e) {
        e.preventDefault();
        var roomIdUsername = document.querySelector('#myForm input[name=roomId]');
        var roomId = roomIdUsername.value;
        if (roomId == "") {
            alert('房间号码不能为空');
            return;
        }
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status == 200) {
                    var result = JSON.parse(this.responseText);
                    if (result.error == 1) {
                        alert(result.message);
                    } else {
                        window.location.href = '../html/liaotian.php?roomId='+roomId;

                    }
                } else {
                    console.log("异常");
                }
            }
        };
        xhr.open(myFormElement.method, myFormElement.action);
        var data = new FormData();
        data.append('roomId', roomId);
        xhr.send(data);
    }
</script>
</body>
</html>